package com.xht.controller;

import com.xht.domain.ResponseResult;
import com.xht.domain.entity.LoginUser;
import com.xht.domain.entity.Menu;
import com.xht.domain.entity.User;
import com.xht.enums.AppHttpCodeEnum;
import com.xht.exception.SystemExceptin;
import com.xht.service.LoginService;
import com.xht.service.MenuService;
import com.xht.service.RoleService;
import com.xht.utils.BeanCopyUtils;
import com.xht.utils.SecurityUtils;
import com.xht.vo.AdminUserInfoVo;
import com.xht.vo.RouterVo;
import com.xht.vo.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class LoginController {
    @Autowired
    private LoginService loginService;

    @Autowired
    private MenuService menuService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private StringRedisTemplate redisTemplate;


    /**
     * 管理员登录校验
     */
    @PostMapping("/user/login")
    public ResponseResult login(@RequestBody User user) {
        //一些基本校验
        if (!StringUtils.hasText(user.getUserName())) {
            //提示 需要传 用户名
            throw new SystemExceptin(AppHttpCodeEnum.REQUIRE_USERNAME);
        }
        return loginService.login(user);
    }

    @GetMapping("getInfo")
    public ResponseResult<AdminUserInfoVo> getInfo() {
        //获取当前登录用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userId = SecurityUtils.getUserId();
        //根据用户id查询权限信息
        List<String> perms = menuService.selectPermsByUserId(userId);
        //更具用户id查询角色信息
        List<String> roleKeyList = roleService.selectRoleKeyByUserId(userId);

        //获取用户信息
        User user = loginUser.getUser();
        UserInfo userInfo = BeanCopyUtils.copyBean(user, UserInfo.class);

        AdminUserInfoVo adminUserInfoVo = new AdminUserInfoVo(perms, roleKeyList, userInfo);
        return ResponseResult.okResult(adminUserInfoVo);
    }

    /**
     * 前端为了实现动态路由的效果,需要后端能返回用户所能访问的菜单数据
     */
    @GetMapping("getRouters")
    public ResponseResult<RouterVo> getRouters() {
        Long userId = SecurityUtils.getUserId();
        //查询menu 结果是tree的形式
        List<Menu> menus = menuService.selectRouterMenuTreeByUserId(userId);
        //封装数据返回
        return ResponseResult.okResult(new RouterVo(menus));

    }

    /**
     * 退出登录
     *
     * @return
     */
    @PostMapping("/user/logout")
    public ResponseResult logout() {

        return loginService.logout();

    }
}
